package com.yyfax.pay.order.controller.web;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.yyfax.commons.lang.BeanUtil;
import com.yyfax.framework.exception.YYException;
import com.yyfax.framework.spring.annotation.JsonParam;
import com.yyfax.framework.yyfax.enums.RspCodeEnum;
import com.yyfax.pay.common.constants.PayConstants;
import com.yyfax.pay.common.enums.PayRspCodeEnum;
import com.yyfax.pay.config.data.service.MerchantConfigService;
import com.yyfax.pay.config.model.po.MerchantConfigPO;
import com.yyfax.pay.order.data.service.AuthOrderService;
import com.yyfax.pay.order.data.service.UserAuthService;
import com.yyfax.pay.order.model.po.AuthOrderPO;
import com.yyfax.pay.order.model.po.UserAuthPO;
import com.yyfax.pay.order.model.to.AuthOrderParams;
import com.yyfax.pay.order.model.to.AuthParams;
import com.yyfax.pay.order.service.AuthService;

/**
 * 独立鉴权控制类
 * 
 * @author buyi
 * @date 2017-04-15 16:24:17
 * @since v1.0.0
 */
@Controller
public class AuthWebController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AuthService authService;

	@Autowired
	private MerchantConfigService merchantConfigService;

	@Autowired
	private UserAuthService userAuthService;

	@Autowired
	private AuthOrderService authOrderService;

	@Autowired
	private PayConstants payConstants;

	/**
	 * TODO 测试，发布需要删除
	 * 
	 * @author buyi
	 * @date 2017-05-03 15:51:01
	 * @since v1.0.0
	 * @return
	 */
	// @RequestMapping({ "/auth" })
	// public String index() {
	// return "authtest";
	// }

	/**
	 * 独立鉴权网关模式
	 * 
	 * @author buyi
	 * @date 2017-04-27 16:41:51
	 * @since v1.0.0
	 * @param sign
	 * @param params
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping(method = RequestMethod.POST, path = "/web/auth/gateway")
	public ModelAndView authGateway(String sign, @JsonParam("params") AuthOrderParams params) throws Throwable {
		logger.debug("enter auth page ……");

		if (StringUtils.isBlank(sign) || params == null) {
			throw new YYException(RspCodeEnum.COMMON_ERROR_PARAMETER_INVALID);
		}

		// 1.校验参数
		params.validate();

		// 2.校验签名
		MerchantConfigPO merchantConfigPO = merchantConfigService.queryByMerchantCode(params.getMerchantCode());
		if (merchantConfigPO == null) {
			throw new YYException(PayRspCodeEnum.PAY_CODE_MERCHANT_NOT_EXISTS, params.getMerchantCode());
		}

		// 3.验签
		String srcSign = params.sign(merchantConfigPO.getSignKey());
		if (!StringUtils.equals(srcSign, sign)) {
			throw new YYException(RspCodeEnum.COMMON_ERROR_NO_SIGN_AUTHENTICATION);
		}

		// 4.校验用户鉴权信息是否存在
		UserAuthPO userAuthPO = userAuthService.queryByUserIdAndMerchantCode(params.getUserId(), params.getMerchantCode());
		if (userAuthPO != null) {
			throw new YYException(PayRspCodeEnum.PAY_CODE_AUTH_IS_CONFIRMED);
		}

		userAuthService.checkIdNoAndName(params.getMerchantCode(), params.getUserId(), params.getIdNo(), params.getName());

		// 3.持久化鉴权订单,以及支付通道路由
		AuthOrderPO authOrderPO = authService.saveAuthOder(params);

		AuthParams authParams = new AuthParams();
		authParams.setAuthOrderId(authOrderPO.getAuthOrderId());
		authParams.setMerchantCode(params.getMerchantCode());
		authParams.setUserIp(params.getUserIp());
		authParams.setPaymentCode(params.getPaymentCode());
		authParams.setOrderId(params.getOrderId());
		authParams.setIdNo(params.getIdNo());
		authParams.setName(params.getName());
		authParams.setCardNo(params.getCardNo());
		authParams.setSign(authParams.sign(payConstants.getSignKey()));

		// 返回视图
		ModelAndView mav = new ModelAndView();
		mav.addAllObjects(BeanUtil.toMap(authParams));
		mav.setViewName("redirect:/auth/counter");

		return mav;
	}

	/**
	 * 跳转到鉴权页面
	 * 
	 * @author buyi
	 * @date 2017-04-17 17:56:44
	 * @since v1.0.0
	 * @param mav
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/web/auth/counter" })
	public ModelAndView authCounter(AuthParams authParams) throws Exception {
		authParams.validate();

		authParams.checkSign(payConstants.getSignKey());

		// 查找鉴权订单信息
		AuthOrderPO authOrderPO = authOrderService.queryByOrderIdAndMerchantCode(authParams.getOrderId(), authParams.getMerchantCode());
		if (authOrderPO == null) {
			logger.error("鉴权订单不存在。orderId：{},merchantCode:{}", authParams.getOrderId(), authParams.getMerchantCode());
			throw new YYException(PayRspCodeEnum.COMMON_ERROR_OBJECT_NOT_FOUND);
		}

		ModelAndView mav = new ModelAndView();
		mav.addAllObjects(BeanUtil.toNonEmptyMap(authParams));
		mav.setViewName("auth");
		return mav;
	}
}
